class Lily

	class Updater
		def self.update(title, content, filepath, mtime, update_mtime)
			File.open(filepath, 'w') {|fh|
				fh.flock(File::LOCK_EX)
				fh.write [title, content].join("\n")
				fh.flock(File::LOCK_UN)
			}

			current_mtime = File.mtime(filepath)

			if (update_mtime && update_mtime != '')
				mtime = Time.now

				if (mtime && mtime.strftime(@date_format) != current_mtime.strftime(@date_format))
					mtime = current_mtime
				end

				File.utime(mtime, mtime)
			else
				File.utime(current_mtime, current_mtime)
			end
		end
	end

end


def update
	return unless @editable_extension.index(@options.flavour)
	return unless @cgi.params['mode'][0] == 'update'

	title = @cgi.params['title'][0]
	content = @cgi.params['content'][0]
	cat = @cgi.params['category'][0]
	category = (cat && cat != '') ? cat + '/' : ''
	fn = @cgi.params['filename'][0]
	ext = @file_extension.detect {|ex| File.exist?("#{@datadir}/#{category}#{fn}.#{ex}") }
	fp = "#{@datadir}/#{category}#{fn}.#{ext}"
	umtime = @cgi.params['update_mtime'][0]
	mtime = @cgi.params['time'][0]

	Lily::Updater.update(title, content, fp, mtime, umtime)
end
